'use strict'
import { app, protocol, BrowserWindow, Menu } from 'electron'
import { ipcMain, ipcRenderer } from "electron"
const dialog = require('electron').dialog;
const path = require('path');
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const MainGlobalVar = {};
const Tray = require('electron').Tray
global = {};
global.appName = '携客云打标系统';
var appTray = null;
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
    // Create the browser window.

    let trayMenuTemplate = [{
            label: '刷新',
            role: 'forcereload'

        },
        {
            label: '退出',
            click: function() {
                app.exit();
            }
        }
    ];
    let contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
    appTray = new Tray(path.join(app.getAppPath(), 'desktopapp.ico'));
    appTray.setToolTip('携客云打标系统');

    appTray.setContextMenu(contextMenu);


    appTray.on('click', function() {
        win.maximize();

    });

    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            //nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
            //contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
            nodeIntegration: true,
            nodeIntegrationInWorker: true,
            contextIsolation: false,
            webSecurity: false,
            webviewTag: true,
            javascript: true,
            
            preload: __dirname + '/preload.js'

        }
    })

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
        // await win.loadURL("https://echat.dianbafang.com/offline");
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        //createProtocol('app')
        // Load the index.html when not in development
        // win.loadURL('app://./index.html')
        win.loadURL("https://dabiao.roctc.com")
    }
    MainGlobalVar.mainWin = win;
    MainGlobalVar.mainWin.webContents.send("rootFilePath", path.resolve(__dirname));
    win.on("close", (e) => {

        e.preventDefault();
        dialog.showMessageBox(win, {
            type: "info",
            title: "是否退出",
            message: "是否退出打标系统",
            defaultId: 0,
            buttons: [
                '最小化', '直接退出'
            ]
        }).then(result => {

            if (result.response === 0) {
                e.preventDefault();
                win.minimize();
            } else {
                app.exit();
            }
        });
    });
    win.on('closed', () => {
        win = null
    });
    win.maximize();
    win.show();

}

function init() {

    ipcMain.on("openFile", (event, filepath) => {



        dialog.showOpenDialog(MainGlobalVar.mainWin,{
            properties: ['openDirectory'],
            defaultPath: filepath ? filepath : path.resolve(__dirname)
        }).then(result => {
            if (!result.canceled) {
                console.log(result.filePaths[0]); // 选择的文件夹路径
                MainGlobalVar.mainWin.webContents.send("setFilePath", result.filePaths[0]);
            }
        }).catch(err => {
            console.error(err);
        });



    });
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {

    if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        try {
            // await installExtension(VUEJS3_DEVTOOLS)
        } catch (e) {
            console.error('Vue Devtools failed to install:', e.toString())
        }
    }
    createWindow();
    init();

})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}





